<?php


namespace models\Business;


use models\Exception\Business\LocationException;
use Yaf\Exception;
use Yaf\Registry;
use youliPhpLib\Common\RequestHelper;

class Location
{
    const GET_LOCATION_BY_NAME_URL = "https://ali-city.showapi.com/areaName";
    const GET_LOCATION_BY_PARENT_URL = "https://ali-city.showapi.com/areaDetail";
    const APP_KEY = "203802317";
    const APP_CODE = "34bb256a03ce4caba2c79138272c6229";
    const APP_SECRET = "f2b8pet9tjz0irzrl66o5rw7knb8m2kf";

    /**
     * 获取省市区县街道数据
     * @param string $parent_code 上级行政单位的身份证号前12位
     * @param int $level 级别 获取省份为1，获取城市为2，获取区县为3，获取接到为4
     * @param int $page 获取省份时才需要
     * @return array
     * @throws LocationException
     */
    static public function getLocation($parent_code = '', $level = 1, $page = 1) {
        $get_all = false;
        if (!empty($parent_code)) {
            $param['parentId'] = $parent_code;
            $param['level'] = $level;
            $param['page'] = 1;
        } else {
            $param['level'] = $level;
            $param['page'] = $page;
            $get_all = true;
        }
        $param['maxSize'] = 20;
        $cache_name = $get_all === true ? 'province' : ($level == 2 ? 'city' :
            ($level == 3 ? 'area' : ($level == 4 ? 'street:' : '')));
        if (empty($cache_name))
            throw new LocationException(LocationException::CACHE_NAME_EMPTY, LocationException::CACHE_NAME_EMPTY_NO);

        $cache_name .= !empty($parent_code) ? ':'.$parent_code : '';
        $data = Registry::get('redis_sorted_set')->getSortedSet($cache_name);
        if ($data) {
            foreach ($data as $idx => $row)
                $data[$idx] = json_decode($row, true);
        } else {
            if ($get_all === true)
                $url = self::GET_LOCATION_BY_NAME_URL . '?' . http_build_query($param);
            else
                $url = self::GET_LOCATION_BY_PARENT_URL . '?' . http_build_query($param);

            $header = ['Authorization:APPCODE ' . self::APP_CODE];
            list($header_size, $body) = RequestHelper::curlRequest($url, '', 'GET', $header);

            $resp = substr($body, $header_size);
            $resp_arr = json_decode($resp, true);
            if (isset($resp_arr['showapi_res_body']) && $resp_arr['showapi_res_body']['ret_code'] == 0) {
                $data = $store_data = [];
                $i = 1;
                foreach ($resp_arr['showapi_res_body']['data'] as $row) {
                    if ($page == 1)
                        array_push($store_data, json_encode(['name' => $row['areaName'], 'code' => $row['id']]));
                    else {
                        $store_data[$param['maxSize'] * ($page - 1) + $i] = json_encode(['name' => $row['areaName'], 'code' => $row['id']]);
                        $i++;
                    }
                    array_push($data, ['name' => $row['areaName'], 'code' => $row['id']]);
                }

                if (!empty($store_data))
                    Registry::get('redis_sorted_set')->genSortedSet($cache_name, $store_data);
            }
        }

        return $data;
    }

}
